//package com.zz.webapp.util;
//
//import com.dtdream.commons.lang.LinkedList;
//import com.dtdream.commons.utils.args.Arguments;
//import com.dtdream.dop.lead.model.LeadUnique;
//import com.google.common.base.Throwables;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.core.convert.converter.Converter;
//import org.springframework.core.serializer.support.DeserializingConverter;
//import org.springframework.core.serializer.support.SerializingConverter;
//import org.springframework.dao.DataAccessException;
//import org.springframework.data.redis.connection.RedisConnection;
//import org.springframework.data.redis.core.RedisCallback;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.core.TimeoutUtils;
//import org.springframework.data.redis.serializer.RedisSerializer;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.Resource;
//import java.util.List;
//import java.util.concurrent.TimeUnit;
//
///**
// * Created by anson on 2016/10/31.
// */
//@Slf4j
//@Component
//public class LeadRedisTemplate {
//    public static final String GrabModule = "Grab";
//
//    @Resource(name = "redisTemplate")
//    private RedisTemplate redisTemplate;
//
//    private Converter<Object, byte[]> serializer = new SerializingConverter();
//
//    private Converter<byte[], Object> deserializer = new DeserializingConverter();
//
//
//    /* 获取缓存key的接口 */
//    public byte[] getRedisKey(Long id, String module) {
//        if (null == id){
//            return null;
//        }
//        StringBuilder key = new StringBuilder();
//        key.append(module)
//                .append(String.valueOf(id));
//
//        return key.toString().getBytes();
//    }
//
//
//    /* 删除已有key */
//    public void deleteSpecifyRedisKey(Long id, String module) {
//        if (null == id){
//            return;
//        }
//        byte[] key = getRedisKey(id, module);
//        /* 如果存在相关的key则删除 */
//        if (!Arguments.isNull(getGrabRedisInfo(id))) {
//            redisTemplate.execute(new RedisCallback<Object>() {
//                public Object doInRedis(RedisConnection connection) {
//                    connection.del(key);
//                    return null;
//                }
//            }, true);
//        }
//        log.info("Lead[]deleteSpecifyRedisKey 删除redis key成功, key:{}, data:{}", key);
//    }
//
//    public void createRedisKey(LeadUnique leadUnique) {
//        if (null == leadUnique) {
//            return;
//        }
//        try {
//            Long leadUniqueId = leadUnique.getLeadUniqueId();
//            byte[] key = getRedisKey(leadUniqueId, LeadRedisTemplate.GrabModule);
//            List<LeadUnique> leadUniques = new LinkedList<>();
//            byte[] leadValue = serializer.convert(leadUniques);
//            redisTemplate.execute(new RedisCallback() {
//                @Override
//                public Object doInRedis(RedisConnection connection) throws DataAccessException {
//                    connection.setEx(key, TimeoutUtils.toSeconds(30, TimeUnit.MINUTES), leadValue);
//                    return null;
//                }
//            });
//            log.info("Lead[]createRedisKey 创建redis key成功, key:{}, data:{}", key, leadValue);
//        }catch (Exception e) {
//            log.error("Lead[]createRedisKey 创建redis key失败, cause:{}", Throwables.getStackTraceAsString(e));
//        }
//    }
//
//    /* 检测是否已存在缓存信息 */
//    public boolean isExistGrabInfo(LeadUnique leadUnique) {
//        if ((null == leadUnique) || (null == leadUnique.getLeadUniqueId()) || (null == leadUnique.getConsultantId())) {
//            return true;
//        }
//
//        try {
//            Long leadUniqueId = leadUnique.getLeadUniqueId();
//            byte[] key = getRedisKey(leadUniqueId, LeadRedisTemplate.GrabModule);
//            if(Arguments.isNullOrEmpty(getGrabRedisInfo(leadUniqueId))){
//                log.info("lead[]LeadRedisTemplate[]the gran time is out, cannot grab lead!");
//                return false;
//            }
//            List<LeadUnique> leadUniques = getGrabRedisInfo(leadUniqueId);
//            boolean isExist = false;
//            for (LeadUnique temp : leadUniques) {
//                if (temp.getConsultantId().equals(leadUnique.getConsultantId())) {
//                    log.info("lead[]LeadRedisTemplate[]already exist the same lead!");
//                    isExist = true;
//                    break;
//                }
//            }
//            return isExist;
//        }catch (Exception e) {
//            log.error("Lead[]LeadRedisTemplate[]isExistGrabInfo 缓存判断异常, cause:{}", Throwables.getStackTraceAsString(e));
//        }
//
//        return true;
//    }
//
//    /* 缓存抢单信息 */
//    public void redisGrabInfo(LeadUnique leadUnique) {
//        if (null == leadUnique) {
//            return;
//        }
//
//        try {
//            Long leadUniqueId = leadUnique.getLeadUniqueId();
//            if(!Arguments.isNull(getGrabRedisInfo(leadUniqueId))){
//                byte[] key = getRedisKey(leadUniqueId,LeadRedisTemplate.GrabModule);
//                List<LeadUnique> leadUniques = getGrabRedisInfo(leadUniqueId);
//                leadUniques.add(leadUnique);
//                byte[] value = serializer.convert(leadUniques);
//                redisTemplate.execute(new RedisCallback() {
//                    @Override
//                    public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
//                        redisConnection.setEx(key,TimeoutUtils.toSeconds(30,TimeUnit.MINUTES),value);
//                        return null;
//                    }
//                },true);
//            }else{
//                log.error("Lead[]LeadRedisTemplate[]redisGrabInfo[]找不到对应的key：{}", leadUniqueId);
//            }
////            ValueOperations<String, List<LeadUnique>> redisData = this.redisTemplate.opsForValue();
////            if (!Arguments.isNull(redisData.get(key))) {
////                List<LeadUnique> oldData = redisData.get(key);
////                oldData.add(leadUnique);
////                /* 缓存key与数据之前的关系 */
////                redisData.set(key, oldData);
////                log.info("Lead[]LeadRedisTemplate[]redisGrabInfo[]缓存成功[]key:{}, data:{}", key, redisData.get(key));
////            }else {
////                log.error("Lead[]LeadRedisTemplate[]redisGrabInfo[]找不到对应的key：{}", key);
////            }
//        }catch (Exception e) {
//            log.error("Lead[]LeadRedisTemplate 缓存抢单列表异常, cause:{}", Throwables.getStackTraceAsString(e));
//        }
//    }
//    /* 获取抢单队列信息 */
//    public List<LeadUnique> getGrabRedisInfo(Long inputKey) {
//        log.info("Lead[]LeadRedisTemplate[]getGrabRedisInfo input key is: {}", inputKey);
//        if (null == inputKey) {
//            return null;
//        }
//        byte[] key = getRedisKey(inputKey, LeadRedisTemplate.GrabModule);
//        return (List<LeadUnique>)redisTemplate.execute(new RedisCallback() {
//            @Override
//            public List<LeadUnique> doInRedis(RedisConnection redisConnection) throws DataAccessException {
//                byte[] value = redisConnection.get(key);
//                if(null == value){
//                    return null;
//                }
//                List<LeadUnique> leadUniques =(List<LeadUnique>) deserializer.convert(value);
//                return leadUniques;
//            }
//        });
//
//    }
//
//    private int retryTimes = 0;
//    private final int baseMilliInterval = 100;
//    /* 给redis加锁 */
//    public Boolean getRedisLock(final String key, final int time, final String businessId) {
//        boolean result = (boolean) redisTemplate.execute(new RedisCallback<Boolean>() {
//            @Override
//            public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
//                RedisSerializer<String> stringRedisSerializer = redisTemplate.getStringSerializer();
//                byte[] keyBytes = stringRedisSerializer.serialize(key + "_Lock");
//                byte[] value = stringRedisSerializer.serialize(businessId);
//                retryTimes = (time * 1000 / baseMilliInterval);
//                Boolean canGetLock = Boolean.FALSE;
//                for (int i = 0; i < retryTimes; i ++) {
//                    canGetLock = redisConnection.setNX(keyBytes, value);
//                    if (canGetLock) {
//                        redisConnection.expire(keyBytes, time);
//                        break;
//                    }else {
//                        log.info("lead[]LeadRedisTemplate[]cannot get redis lock! waiting! key:{}, 次数:{}", key, i);
//                        try {
//                            Thread.sleep(100);  //休眠100ms
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//
//                return canGetLock;
//            }
//        });
//
//        return result;
//    }
//    /* 释放redis锁 */
//    public void releaseRedisLock(final String key, final String businessId) {
//        redisTemplate.execute(new RedisCallback<Boolean>() {
//            @Override
//            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
//                RedisSerializer<String> stringRedisSerializer = redisTemplate.getStringSerializer();
//                byte[] keyBytes = stringRedisSerializer.serialize(key + "_Lock");
//                byte[] value = connection.get(keyBytes);
//                if ((value != null) && (new String(value).equals(businessId))) {
//                    log.info("lead[]LeadRedisTemplate[]releaseRedisLock, key:{}", key);
//                    return connection.del(keyBytes) == 1L;
//                }else {
//                    return false;
//                }
//            }
//        });
//    }
//}
